package com.example.lottery.controller;

import com.example.lottery.common.errorcode.ControllerErroeCodeConstants;
import com.example.lottery.common.exception.ControllerException;
import com.example.lottery.common.pojo.CommonResult;
import com.example.lottery.common.utils.JacksonUtil;
import com.example.lottery.controller.param.ShortMessageLoginParam;
import com.example.lottery.controller.param.UserPasswordLoginParam;
import com.example.lottery.controller.param.UserRegisterParam;
import com.example.lottery.controller.result.BaseUserInfoResult;
import com.example.lottery.controller.result.UserLoginResult;
import com.example.lottery.controller.result.UserRegisterResult;
import com.example.lottery.service.UserService;
import com.example.lottery.service.VerificationCodeService;
import com.example.lottery.service.dto.UserDTO;
import com.example.lottery.service.dto.UserLoginDTO;
import com.example.lottery.service.dto.UserRegisterDTO;
import com.example.lottery.service.enums.UserIdentityEnum;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@Slf4j
public class UserController{
    @Autowired
    private VerificationCodeService verificationCodeService;
    @Autowired
//    UserService 是一个接口，直接使用 @Autowired 注入接口本身在 Spring 中是不允许的，因为接口无法被实例化。
    //当 Spring 看到 @Autowired private UserService userService; 时，
    // 会自动查找实现了 UserService 接口的 Bean（也就是 UserServiceImpl），并完成注入。
    private UserService userservice;


    @RequestMapping("/register")
    public CommonResult<UserRegisterResult> userRegister(@Validated @RequestBody
                                                         UserRegisterParam param){
        log.info("注册传递的对象param:{}", JacksonUtil.writeValueAsString(param));//变成json字符串,序列化
        UserRegisterDTO userRegisterDTO = userservice.register(param);
        return CommonResult.success(convertToRegisterResult(userRegisterDTO));
    }
    private UserRegisterResult convertToRegisterResult(UserRegisterDTO userRegisterDTO) {
        if(userRegisterDTO==null){
            throw new ControllerException(ControllerErroeCodeConstants.REGISTER_ERROR);
        }
        UserRegisterResult userRegisterResult=new UserRegisterResult();
        userRegisterResult.setUserId(userRegisterDTO.getUserId());
        return userRegisterResult;
    }

    /**
     * 发送验证码
     * @param phoneNumber
     * @return
     */
    @RequestMapping("/verification-code/send")
    public CommonResult<Boolean> sendVerificationCode(String phoneNumber) {
        log.info("sendVerificationCode phoneNumber:{}", phoneNumber);
        verificationCodeService.sendVerificationCode(phoneNumber);
        //相当于返回的就是true，只不过装箱了，你写true也会自动装箱
        //这里使用Boolean.TRUE 适用于泛型
        return CommonResult.success(Boolean.TRUE);
    }

    /**
     * 用密码进行登陆
     * @param param
     * @return
     */
    @RequestMapping("/password/login")
    public CommonResult<UserLoginResult> userPasswordLogin(@Validated @RequestBody
                                                           UserPasswordLoginParam param){
        log.info("userPasswordLogin UserPasswordLoginParam:{}",JacksonUtil.writeValueAsString(param));
        UserLoginDTO userLoginDTO=userservice.login(param);
        return CommonResult.success(convertToUserLoginResult(userLoginDTO));
    }

    private UserLoginResult convertToUserLoginResult(UserLoginDTO userLoginDTO) {
        if(userLoginDTO==null){
            throw new ControllerException(ControllerErroeCodeConstants.LOGIN_ERROR);
        }
        UserLoginResult result=new UserLoginResult();
        result.setToken(userLoginDTO.getToken());
//        如果 userLoginDTO.getIdentity() 返回 UserIdentityEnum.ADMIN，那么 .name() 就返回字符串 "ADMIN"。
        result.setIdentity(userLoginDTO.getIdentity().name());
        return result;
    }

    /**
     * 短信验证码登陆
     * @param param
     * @return
     */
    @RequestMapping("/message/login")
    public CommonResult<UserLoginResult> shortMessageLogin(@Validated @RequestBody
                                                           ShortMessageLoginParam param){
        log.info("shortMessageLogin ShortMessageLoginParam:{}",JacksonUtil.writeValueAsString(param));
        UserLoginDTO userLoginDTO=userservice.login(param);
        return CommonResult.success(convertToUserLoginResult(userLoginDTO));
    }
    @RequestMapping("/base-user/find-list")
    public CommonResult<List<BaseUserInfoResult>> findBaseUserInfo(String identity) {
        log.info("findBaseUserInfo identity:{}",identity);
        List<UserDTO> userDTOList=userservice.findUserInfo(
                UserIdentityEnum.forName(identity));
        return CommonResult.success(convertToList(userDTOList));
    }

    private List<BaseUserInfoResult> convertToList(List<UserDTO> userDTOList) {
        if(CollectionUtils.isEmpty(userDTOList)){
            //如果为空，则返回一个空的列表即可
            return Arrays.asList();
        }
        //利用流之间的映射，最后再次重新转换为list
        return userDTOList.stream()
                .map(userDTO -> {
                    BaseUserInfoResult baseUserInfoResult=new BaseUserInfoResult();
                    baseUserInfoResult.setUserId(userDTO.getUserId());
                    baseUserInfoResult.setUserName(userDTO.getUserName());
                    baseUserInfoResult.setIdentity(userDTO.getIdentity().name());
                    return baseUserInfoResult;
                }).collect(Collectors.toList());
    }


}
